

from django.utils import timezone
from django.http import HttpResponseRedirect, HttpResponse
# 订单相关视图：包含订单列表、详情、创建
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from LogisticsCard.models import CardOrder, Cards
from django.contrib.auth.models import User
from LogisticsCard.utils.wechatpay import WXPay
from django.views.decorators.http import require_http_methods
from django.contrib import messages
from LogisticsCard.permission_dict import operator_cn, card_status_cn, card_type_cn, real_name_auth_cn
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import csv


@login_required
def order_list_view(request):
    """
    订单列表视图，展示所有订单。
    :param request: HttpRequest对象
    :return: 渲染订单列表页面
    """
    orders = CardOrder.objects.filter(delete_at__isnull=True).order_by('-created_at')
    paginator = Paginator(orders, 10)  # 每页10条
    page = request.GET.get('page')
    try:
        page_obj = paginator.page(page)
    except PageNotAnInteger:
        page_obj = paginator.page(1)
    except EmptyPage:
        page_obj = paginator.page(paginator.num_pages)
    return render(request, 'orders/index.html', {'page_obj': page_obj})


@login_required
def order_detail_view(request, order_id):
    """
    订单详情视图，展示指定订单信息。
    :param request: HttpRequest对象
    :param order_id: 订单ID
    :return: 渲染订单详情页面
    """
    order = get_object_or_404(CardOrder, id=order_id)
    return render(request, 'orders/detail.html', {'order': order})


@login_required
def order_create_view(request):
    """
    订单创建视图，处理订单表单提交。
    :param request: HttpRequest对象
    :return: 渲染订单创建页面或跳转到详情
    """
    from LogisticsCard.models import Customer, Address, UserPriceConfig
    user = request.user
    is_admin = hasattr(user, 'profile') and user.profile.type == 'admin'
    customers = Customer.objects.filter(delete_at__isnull=True) if is_admin else None
    customer = None
    address_obj = None
    price_configs = None
    selected_customer_id = None
    selected_package = None
    selected_price = None
    receiver = ''
    delivery_phone = ''
    delivery_address = ''
    card_count = 1
    amount = 0
    remark = ''
    if request.method == 'POST':
        card_count = int(request.POST.get('card_count', 1))
        amount = float(request.POST.get('amount', 0))
        remark = request.POST.get('remark', '')
        selected_package = request.POST.get('package')
        receiver = request.POST.get('receiver', '')
        delivery_phone = request.POST.get('delivery_phone', '')
        delivery_address = request.POST.get('delivery_address', '')
        if not selected_package:
            messages.error(request, '请选择套餐！')
            return render(request, 'orders/create.html', {
                'customers': customers,
                'price_configs': price_configs,
                'receiver': receiver,
                'delivery_phone': delivery_phone,
                'delivery_address': delivery_address,
                'card_count': card_count,
                'amount': amount,
                'remark': remark,
                'selected_package': selected_package,
                'selected_customer_id': selected_customer_id
            })
        if is_admin:
            selected_customer_id = request.POST.get('customer_id')
        else:
            selected_customer_id = None
        customer = Customer.objects.filter(id=selected_customer_id, delete_at__isnull=True).first() if selected_customer_id else getattr(user, 'customer', None)
        address_obj = Address.objects.filter(customer=customer, delete_at__isnull=True).first() if customer else None
        price_configs = UserPriceConfig.objects.filter(customer=customer, delete_at__isnull=True) if customer else None
        # 自动计算金额
        if selected_package and price_configs:
            config = price_configs.filter(package=selected_package).first()
            if config:
                selected_price = float(config.price)
                if not amount or amount == 0:
                    amount = selected_price * card_count
        # 生成订单号：D+20位时间（年月日时分秒毫秒）+4位随机数
        from datetime import datetime
        import random
        now = datetime.now()
        time_str = now.strftime('%Y%m%d%H%M%S%f')[:20]
        rand_str = f"{random.randint(0, 9999):04d}"
        order_no = f"D{time_str}{rand_str}"
        order = CardOrder.objects.create(
            order_no=order_no,
            customer=customer,
            package=selected_package,
            card_count=card_count,
            amount=amount,
            status='pending',
            remark=remark,
            receiver=receiver,
            delivery_phone=delivery_phone,
            delivery_address=delivery_address
        )
        return redirect(f'/order/pay/{order.id}/')
    # GET请求时自动带出客户收货信息和套餐配置（支持切换客户）
    if is_admin:
        selected_customer_id = request.GET.get('customer_id') or (customers.first().id if customers and customers.exists() else None)
    else:
        selected_customer_id = None
    customer = Customer.objects.filter(id=selected_customer_id, delete_at__isnull=True).first() if selected_customer_id else getattr(user, 'customer', None)
    address_obj = Address.objects.filter(customer=customer, delete_at__isnull=True).first() if customer else None
    price_configs = UserPriceConfig.objects.filter(customer=customer, delete_at__isnull=True) if customer else None
    if address_obj:
        receiver = address_obj.receiver
        delivery_phone = address_obj.phone
        delivery_address = address_obj.address
    return render(request, 'orders/create.html', {
        'customers': customers,
        'price_configs': price_configs,
        'receiver': receiver,
        'delivery_phone': delivery_phone,
        'delivery_address': delivery_address,
        'card_count': card_count,
        'amount': amount,
        'remark': remark,
        'selected_package': selected_package,
        'selected_customer_id': selected_customer_id
    })


def order_pay_view(request, order_id):
    order = get_object_or_404(CardOrder, id=order_id)
    wxpay = WXPay()
    # body内容根据订单类型显示
    if hasattr(order, 'order_type') and order.order_type == 'renew':
        body = f'续费订单{order.order_no}'
    else:
        body = f'购卡订单{order.order_no}'
    resp = wxpay.unified_order(
        body=body,
        out_trade_no=order.order_no,
        total_fee=int(order.amount * 100)
    )
    # resp['code_url'] 为二维码内容
    return render(request, 'order/wechatpay.html', {'pay_params': resp, 'order': order})

@login_required
def order_cancel_view(request, order_id):
    order = get_object_or_404(CardOrder, id=order_id, delete_at__isnull=True)
    if order.status == 'pending':
        order.delete_at = timezone.now()
        order.save()
    return redirect('order_list')

@login_required
@require_http_methods(["GET", "POST"])
def order_edit_view(request, order_id):
    from LogisticsCard.models import UserPriceConfig
    order = get_object_or_404(CardOrder, id=order_id, delete_at__isnull=True)
    price_configs = UserPriceConfig.objects.filter(customer=order.customer, delete_at__isnull=True)
    if request.method == "POST":
        # 未支付可全部修改，已支付仅收货信息
        if order.status == "pending":
            order.package = request.POST.get("package", order.package)
            order.card_count = int(request.POST.get("card_count", order.card_count))
            order.amount = float(request.POST.get("amount", order.amount))
            order.remark = request.POST.get("remark", order.remark)
        # paid和pending都可改收货信息
        if order.status in ["pending", "paid"]:
            order.receiver = request.POST.get("receiver", order.receiver)
            order.delivery_phone = request.POST.get("delivery_phone", order.delivery_phone)
            order.delivery_address = request.POST.get("delivery_address", order.delivery_address)
        order.save()
        return redirect(f"/orders/")
    return render(request, "orders/edit.html", {"order": order, "price_configs": price_configs})

@login_required
def order_paid_view(request, order_id):
    order = get_object_or_404(CardOrder, id=order_id, delete_at__isnull=True)
    if order.status == 'pending':
        order.status = 'paid'
        order.paid_at = timezone.now()
        order.save()
    return HttpResponseRedirect(f'/orders/')

@login_required
def order_deliver_view(request, order_id):
    from LogisticsCard.models import Cards, CardUserRelation, CardOrderCard
    order = get_object_or_404(CardOrder, id=order_id, delete_at__isnull=True)
    if order.status == 'paid':
        if order.order_type == 'renew':
            order.status = 'completed'
            order.save()
            messages.success(request, '续费订单已完成。')
        else:
            available_cards = Cards.objects.filter(
                packageName=order.package,
                id__in=Cards.objects.exclude(id__in=CardUserRelation.objects.values_list('card_id', flat=True)),
                delete_at__isnull=True
            )[:order.card_count]
            if available_cards.count() < order.card_count:
                messages.error(request, f'发货失败：可用卡数量不足（需要{order.card_count}，实际{available_cards.count()}），无法发货！')
            else:
                for card in available_cards:
                    CardUserRelation.objects.create(customer=order.customer, card=card)
                    CardOrderCard.objects.create(order=order, card=card)
                    card.save()  # 确保Django ORM刷新缓存
                order.status = 'completed'
                order.save()
                messages.success(request, f'发货成功，已分配{order.card_count}张卡！')
    else:
        messages.error(request, '订单状态不是“已支付”，无法发货！')
    return HttpResponseRedirect('/orders/')

@login_required
def order_cards_view(request, order_id):
    from LogisticsCard.models import CardOrderCard, Cards
    order = get_object_or_404(CardOrder, id=order_id, delete_at__isnull=True)
    card_ids = CardOrderCard.objects.filter(order=order, delete_at__isnull=True).values_list('card_id', flat=True)
    cards = Cards.objects.filter(id__in=card_ids)
    return render(request, 'orders/cards_list.html', {'order': order, 'cards': cards,
        'operator_cn': operator_cn,
        'card_status_cn': card_status_cn,
        'card_type_cn': card_type_cn,
        'real_name_auth_cn': real_name_auth_cn,})

@login_required
def order_cards_export_view(request, order_id):
    from LogisticsCard.models import CardOrderCard, Cards
    from LogisticsCard.permission_dict import card_type_cn, card_status_cn, operator_cn
    order = get_object_or_404(CardOrder, id=order_id, delete_at__isnull=True)
    card_ids = CardOrderCard.objects.filter(order=order, delete_at__isnull=True).values_list('card_id', flat=True)
    cards = Cards.objects.filter(id__in=card_ids)
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = f'attachment; filename="order_{order_id}_cards.csv"'
    writer = csv.writer(response)
    is_admin = request.user.is_superuser or (hasattr(request.user, 'profile') and request.user.profile.type == 'admin')
    header = ['ICCID', 'MSISDN', 'IMSI', 'IMEI', '卡类型', '卡状态', '运营商', '套餐名称']
    if is_admin:
        header.insert(2, '客户')
    writer.writerow(header)
    for card in cards:
        row = [
            card.iccid,
            card.msisdn,
        ]
        if is_admin:
            rels = card.carduserrelation_set.all()
            customer_name = rels[0].customer.username if rels and rels[0].customer else ''
            row.append(customer_name)
        row += [
            card.imsi,
            card.imei,
            card_type_cn.get(str(card.cardType), card.cardType),
            card_status_cn.get(str(card.cardStatus), card.cardStatus),
            operator_cn.get(str(card.operator), card.operator),
            card.packageName
        ]
        writer.writerow(row)
    return response
@login_required
@require_http_methods(["GET", "POST"])
def order_pay_success_view(request, order_id):
    order = get_object_or_404(CardOrder, id=order_id)
    if request.method == "POST":
        return redirect('order_list')
    return render(request, 'order/pay_success.html', {'order': order})